package com.wjm.blog.common.validation;

import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 枚举参数校验处理类
 *
 * @author: Ailos
 * @date: 2020/7/24 9:32
 * @version: 1.0
 */
@Slf4j
public class EnumValidatorForNumber implements ConstraintValidator<EnumValidForNumber, Number> {

    /**
     * 枚举校验注解
     */
    private EnumValidForNumber annotation;

    @Override
    public void initialize(EnumValidForNumber constraintAnnotation) {
        annotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Number value, ConstraintValidatorContext constraintValidatorContext) {
        boolean result = false;

        Class<?> cls = annotation.target();
        boolean ignoreEmpty = annotation.ignoreEmpty();
        String getByCode = annotation.getByCode();

        boolean isNotEmpty = value != null || !ignoreEmpty;

        // target为枚举，并且value有值，或者不忽视空值，才进行校验
        if (cls.isEnum() && isNotEmpty) {
            try {
                Method method = cls.getMethod(getByCode, int.class);
                Object e = method.invoke(null, value);
                if (e == null) {
                    result = false;
                } else {
                    result = true;
                }
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                log.warn("EnumValidatorForNumber call isValid() method exception.");
                result = false;
            }
        } else {
            result = true;
        }
        return result;
    }
}
